<style lang="less">
    @import '../../../styles/common.less';
    @import '../../my-components/data-table/table.less';
</style>

<template>
  <div>
      <Row>
        <Col span="24">
            <Card>
                <p slot="title">
                    <!-- <Icon type="android-more-horizontal"></Icon> -->
                    公司列表
                </p>
                <Row>
                    <Col span="16">
                        <Select  style="width:200px" v-model="searchData.status" clearable>
                            <Option v-for="item in statusDicts" :value="item.id" :key="item.id" :label="item.lable"></Option>
                        </Select>
                        <Button type="primary" shape="circle" icon="ios-search" @click="getData"></Button>
                    </Col>
                    <Col span="3" offset="5" v-if="$hasPerms('company:save')">
                        <span style="margin: 0 10px;">                   
                            <Button type="primary" icon="plus" @click="handleAdd()">新增公司</Button>                          
                        </span>
                    </Col>
                </Row>
                <br>
                <Row>
                    <div class="edittable-table-height-con">
                        <data-table :is-loading="isLoading" v-model="companys" :columns-list="companyColumns"
                                    :total-record="total" :current-page="currentPage" :permissions-prefix="permsSign"
                            @deleteOne="handleDel" @editOne="handleEdit">
                        </data-table>
                    </div>
                </Row>
            </Card>
        </Col>
      </Row>
      <Modal
            v-model="addModal"
            :title="modalTitle"
            :closable='false'
            :mask-closable="false">
        <Form ref="addFrom" :model="addFrom" label-position="top" :rules="rules">
            <FormItem label="公司名" prop="name" >
                <Input v-model="addFrom.name" />
            </FormItem>
            <FormItem label="联系人">
                <Input v-model="addFrom.contacts" />
            </FormItem>
            <FormItem label="联系电话">
                <Input v-model="addFrom.contactsPhone" />
            </FormItem>
            <FormItem label="状态" >
                <Select  style="width:200px" v-model="addFrom.status" >
                    <Option v-for="item in statusDicts" :value="item.id" :key="item.id" :label="item.lable"></Option>
                </Select>
            </FormItem>
        </Form>
        <div slot="footer">
            <Button type="text" @click="cancelModal">取消</Button>
            <Button type="primary" :loading="saveLoading" @click="addModalOk">保存</Button>
        </div>
      </Modal>
  </div>

</template>

<script>
import dataTable from '../../my-components/data-table/dataTable.vue';
import expandRow from './company_expand.vue';

export default {
    name: 'company-index',
    components: {
        dataTable,
        expandRow
    },
    data () {
        let validateCompanyName = (rule, value, callback) => {
            // 编辑时，无改变时不检测
            if(!this.isAddCompany && this.addName === value){
                callback()
            } else {
                this.checkCompanyName(value, callback);
            }
        };
        return {
            isLoading: true,
            saveLoading: false,
            isAddCompany: false,
            permsSign: 'company',
            searchData: {},
            // 表头
            companyColumns: [
                {
                    type: 'expand',
                    width: 50,
                    render: (h, params) => {
                        return h(expandRow, {
                            props: {
                                row: params.row
                            }
                        });
                    }
                },
                {
                    title: 'ID',
                    key: 'id',
                    align: 'center'
                },
                {
                    title: '公司',
                    align: 'center',
                    key: 'name'
                },
                // {
                //     title: '证件',
                //     align: 'center',
                //     render: (h, params) => {
                //         const val = params.row;
                //         return h('a',
                //             {
                //                 attrs: {
                //                     href: val.certificates,
                //                     target: '_black'
                //                 }
                //             },
                //             [
                //                 h('img', {
                //                     attrs: {
                //                         src: val.certificates,
                //                         width: '50px',
                //                         height: '50px'
                //                     }
                //                 })
                //             ]
                //         );
                //     }
                // },
                {
                    title: '联系人',
                    align: 'center',
                    key: 'contacts'
                },
                {
                    title: '联系电话',
                    align: 'center',
                    key: 'contactsPhone'
                },
                {
                    title: '状态',
                    align: 'center',
                    render: (h, params) => {
                        const val = params.row;
                        if (val.status === 1) {
                            return h('Tag', {
                                props: {
                                    color: 'yellow'
                                }
                            }, '待审核');
                        } else if (val.status === 2) {
                            return h('Tag', {
                                props: {
                                    color: 'green'
                                }
                            }, '正常');
                        } else if (val.status === 3) {
                            return h('Tag', {
                                props: {
                                    color: 'red'
                                }
                            }, '已拒绝');
                        } else if (val.status === 4) {
                            return h('Tag', {
                                props: {
                                    color: 'black'
                                }
                            }, '已删除');
                        } else {
                            return h('Tag', {
                                props: {
                                    color: 'default'
                                }
                            }, '未知');
                        }
                    }
                },
                {
                    title: '创建时间',
                    align: 'center',
                    key: 'createTime'
                },
                {
                    title: '操作',
                    align: 'center',
                    key: 'handle',
                    handle: ['edit', 'delete']
                }
            ],
            // 数据
            companys: [],
            total: 0,
            currentPage: 1,
            statusDicts: [
                {
                    lable: '待审核',
                    id: 1
                }, {
                    lable: '正常',
                    id: 2
                }, {
                    lable: '已拒绝',
                    id: 3
                }, {
                    lable: '已删除',
                    id: 4
                }
            ],
            modalTitle: '',
            addModal: false,
            addName: '',
            addFrom: {
                id: 0,
                name: '',
                contacts: '',
                contactsPhone: '',
                status: 1
            },
            rules: {
                name: [
                    {required: true, message: '名称不能为空', trigger: 'blur'},
                    { validator: validateCompanyName, trigger: 'blur' }
                ]
            }
        };
    },
    methods: {
        getData () {
            this.$get('/company/list?pageNum=' + this.currentPage, this.searchData)
                .then(res => {
                    this.companys = res.records;
                    this.total = res.total;
                    this.currentPage = res.current;
                    this.isLoading = false;
                })
                .catch(error => {
                    this.isLoading = false;
                });
        },
        cancelModal () {
            this.addModal = false;
        },
        handleAdd () {
            this.isAddCompany = true;
            this.addModal = true;
            this.modalTitle = '新增公司';
            this.addFrom = {
                id: 0,
                name: '',
                contacts: '',
                contactsPhone: '',
                status: 1
            };
        },
        handleEdit (val) {
            this.isAddCompany = false;
            this.addModal = true;
            this.$get('/company/info/' + val.id)
                .then(res => {
                    this.modalTitle = '编辑公司';
                    this.addName = res.name
                    this.addFrom.id = res.id;
                    this.addFrom.name = res.name;
                    this.addFrom.contacts = res.contacts;
                    this.addFrom.contactsPhone = res.contactsPhone;
                    this.addFrom.status = res.status;
                }).catch(error => {
                    this.$Message.error('获取公司信息失败');
                });
        },
        addModalOk () {
            this.$refs.addFrom.validate((valid) => {
                if (valid) {
                    let url = '/company/update';
                    if (this.isAddCompany) {
                        url = '/company/save';
                    }
                    this.saveLoading = true;
                    this.$post(url, {
                        id: this.addFrom.id === 0 ? null : this.addFrom.id,
                        name: this.addFrom.name,
                        contacts: this.addFrom.contacts,
                        contactsPhone: this.addFrom.contactsPhone,
                        status: this.addFrom.status
                    }, 'json')
                        .then(res => {
                            this.getData();
                            this.$Message.success('操作成功');
                            this.addModal = false;
                            this.saveLoading = false;
                        })
                        .catch(error => {
                            this.saveLoading = false;
                            this.$Message.error(error.message);
                        });
                } else {
                    this.saveLoading = false;
                    // 获取表单域所有field
                    let fields = this.$refs.addFrom.fields;
                    // 聚焦错误表单域
                    try {
                        fields.forEach(element => {
                            if (element.validateState === 'error') {
                                // 这里的element无foucs()
                                let refName = element.prop;
                                this.$refs[refName].focus();
                                // 抛出异常跳出循环
                                foreach.break = new Error('StopIteration');
                            }
                        });
                    } catch (e) {
                        console.log(e);
                    }
                }
            });
        },
        handleDel (val, index) {
            // 删除
            let companyIds = [];
            companyIds.push(val.id);
            this.$del('/company/delete',
                companyIds, 'json'
            ).then(res => {
                this.companys.splice(index, 1);
                this.$Message.success('删除了' + val.name);
                this.getData();
            }).catch(error => {
                console.log(error);
                this.$Message.error(error.message);
            });
        },
        handleSelectAll (status) {
            // this.$manager.selection.selectAll(status);
        },
        changePage (page) {
            this.currentPage = page;
            this.getData();
        },
        checkCompanyName(value, callback){
            this.$get('/company/checkName?name=' + value)
                .then(res => {
                    if (res >= 1) {
                        callback(new Error('公司名称已被使用'));
                    } else {
                        callback();
                    }
                })
                .catch(e => {
                    this.sloading = false;
                });
        }
    },
    created () {
        this.getData();
    }
};
</script>
